package com.example.armmvvm.ui.customdraw.view

import android.content.Context
import android.graphics.*
import android.text.TextPaint
import android.util.AttributeSet
import android.view.View
import com.example.arm.ext.dp
import com.example.armmvvm.R
import timber.log.Timber

/**
 * 多行文字
 *
 * @author 创建人 ：yanghaozhang
 * @version 1.0
 * @package 包名 ：com.example.armmvvm.ui.custom
 * @createTime 创建时间 ：2021/9/16
 * @modifyBy 修改人 ：
 * @modifyTime 修改时间 ：
 * @modifyMemo 修改备注：
 */
class DrawMultiLineTextTestView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.FILL
    }

    private val textPaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.BLUE
        typeface = Typeface.SANS_SERIF
        textSize = 18.dp
    }

    private val fontMetrics = Paint.FontMetrics()

    override fun draw(canvas: Canvas) {
        super.draw(canvas)
        paint.color = Color.GRAY
        canvas.drawRect(0f, 0f, width / 2f, height / 2f, paint)
        paint.color = Color.RED
        canvas.drawRect(width / 2f, 0f, width.toFloat(), height / 2f, paint)
        paint.color = Color.YELLOW
        canvas.drawRect(0f, height / 2f, width / 2f, height.toFloat(), paint)
        paint.color = Color.GREEN
        canvas.drawRect(width / 2f, height / 2f, width.toFloat(), height.toFloat(), paint)

        val bitmapTopHeight = 50.dp
        val bitmapWidth = 120.dp
        canvas.drawBitmap(getAvatar(bitmapWidth.toInt()), width - bitmapWidth, bitmapTopHeight, paint)

        val str =
            "Retrieve the text boundary box and store to bounds.检索文本边界框并存储到边界。 Return in bounds (allocated by the caller) the smallest rectangle that encloses all of the characters, with an implied origin at (0,0)."
        val text =
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vel porttitor magna, sit amet ultrices risus. Praesent eu justo in ex convallis venenatis. Donec fermentum iaculis tortor, id dignissim massa tincidunt hendrerit. Maecenas a ornare eros, et malesuada odio. Morbi condimentum sollicitudin nulla, id ullamcorper eros aliquam at. Aenean mauris enim, suscipit at ultrices sit amet, maximus faucibus lacus. Proin egestas consectetur molestie. Ut pharetra, justo non eleifend lobortis, leo dui mollis mi, at placerat nisl nisi non est."
        // staticLayout完成自动换行绘制
/*        val staticLayout = StaticLayout(text, textPaint, width - 20.dpInt, Layout.Alignment.ALIGN_NORMAL, 1f, 0f, false)
        canvas.save()
        canvas.translate(10.dp, 0f)
        staticLayout.draw(canvas)
        canvas.restore()*/

        // 自定义换行
        textPaint.getFontMetrics(fontMetrics)
        //两个方法计算得出的 行距 不一样
        //		getFontSpacing() 的结果并不是通过 FontMetrics 的标准值计算出来的，而是另外计算出来的一个值
        //		它能够做到在两行文字不显得拥挤的前提下缩短行距，以此来得到更好的显示效果。
        //		所以如果你要对文字手动换行绘制，多数时候应该选取 getFontSpacing() 来得到行距，不但使用更简单，显示效果也会更好。
//        val lineHeight = fontMetrics.bottom - fontMetrics.top + fontMetrics.leading
        val lineHeight = textPaint.fontSpacing
        var textY = -fontMetrics.ascent
        var tempStr = text
        val measuredWidth = FloatArray(2)
        var breakTextSize = 0
        while (tempStr.length > breakTextSize) {
            tempStr = tempStr.substring(breakTextSize)
            breakTextSize =
                if (textY + fontMetrics.bottom < bitmapTopHeight || textY + fontMetrics.top > bitmapTopHeight + bitmapWidth) {
                    textPaint.breakText(
                        tempStr,
                        true,
                        width.toFloat(),
                        measuredWidth
                    )
                }
                // 绕过图片
                else {
                    textPaint.breakText(
                        tempStr,
                        true,
                        width.toFloat() - bitmapWidth,
                        measuredWidth
                    )
                }
            canvas.drawText(tempStr.substring(0, breakTextSize), 0f, textY, textPaint)
            textY += lineHeight

            Timber.d(breakTextSize.toString())
            Timber.d(measuredWidth.contentToString())
        }

        Timber.d(lineHeight.toString())
        Timber.d((fontMetrics.bottom - fontMetrics.top).toString())
        Timber.d(text.length.toString())
        Timber.d(width.toString())
    }

    private fun getAvatar(width: Int): Bitmap {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeResource(resources, R.mipmap.icon_avatar, options)
        options.inJustDecodeBounds = false
        options.inDensity = options.outWidth
        options.inTargetDensity = width
        return BitmapFactory.decodeResource(resources, R.mipmap.icon_avatar, options)
    }
}